package com.vsd.service.impl;


import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.demo.domain.Code;
import com.vsd.repository.CodeRepository;
import com.vsd.service.CodeService;

@Service
@Transactional
public class CodeServiceImpl implements CodeService {
	@SuppressWarnings("unused")
	private static final Logger LOGGER = LoggerFactory
			.getLogger(CodeServiceImpl.class);
	
	static Map<String, Code> cache;
	//平台酒水比例
	public static String WINE_RATE;
	//菜品订单超时时间
	public static Integer OUT_TIME;
	//抢购持续时长 分钟
	public static Integer QUICK_TIME;
	
	@Autowired
	CodeRepository codeRepository;
	@Autowired
	JdbcTemplate jdbcTemplate;
	
	private void init(){
		cache = new HashMap<String, Code>();
		Collection<Code> codes = codeRepository.findAll();
		for (Code c : codes) {
			cache.put(c.getCode(), c);
		}
	}
	
	@Override
	public Code getByCode(String code) {
		if(cache==null) init();
		return cache.get(code);
	}

	@Override
	public String getWineRate() {
		if(WINE_RATE==null) WINE_RATE = getByCode("rate@sys").getValue();
		return WINE_RATE;
	}

	@Override
	public Integer getOutTime() {
		if(OUT_TIME==null){
			 Code c = getByCode("10002");
			 if(c==null) return 3;
			 OUT_TIME = new Integer(c.getValue());
		}
		return OUT_TIME;
	}
	
	@Override
	public Integer getQuickTime() {
		if(QUICK_TIME==null){
			 Code c = getByCode("quick@sys");
			 if(c==null) return 3;
			 QUICK_TIME = new Integer(c.getValue());
		}
		return QUICK_TIME;
	}

	@Override
	public Page<Code> findAll(Pageable p) {
		// TODO Auto-generated method stub
		return codeRepository.findAll(p);
	}

	@Override
	public int updateByPrimaryKeySelective(Code code) {
		// TODO Auto-generated method stub
		String sql = " update b_code set value = '"+code.getValue()+"' where code = '"+code.getCode()+"'";
		int c = jdbcTemplate.update(sql);
		init();
		return c;
	}

	@Override
	public Code findOne(String code) {
		// TODO Auto-generated method stub
		return codeRepository.findOne(code);
	}
	
	 
	
}
